﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using XiaoGang.Soft.XGWMS.COM;
using Excel;
using System.IO;
using System.Reflection;
using XiaoGang.Soft.XGWMS.BLL;

namespace XiaoGang.Soft.XGWMS.UI
{
    public partial class M000_System : FormBase
    {
        public M000_System()
        {
            InitializeComponent();
        }

        #region 变量定义        
       
        private const string dataName = "";

        #endregion

        #region 窗口初始化

        protected void SetTableIndex()
        {
            int intIndex = 0;
            btnClose.TabIndex = intIndex; intIndex++;
        }

        /// <summary>
        /// <p><b>方法名称</b>InitialGridView</p>
        /// <p><b>概要説明	:</b>Grid初始化</p>
        /// <p><b>作成者	:</b>万岗</p>
        /// <p><b>作成日	:</b>2008/09/10</p>
        /// </summary>
        protected void InitialGridView()
        {
            
        }

        /// <summary>
        /// <p><b>方法名称</b>InitProcess</p>
        /// <p><b>概要説明	:</b>画面的初期化</p>
        /// <p><b>作成者	:</b>万岗</p>
        /// <p><b>作成日	:</b>2008/09/10</p>
        /// </summary>
        protected void InitProcess()
        {
            InitialGridView();
            SetTableIndex();
            InitDataBackList();
        }

        #endregion

        #region 方法

        /// <summary>
        /// <p><b>方法名称</b>ShowGrid</p>	
        /// <p><b>概要説明  :</b>Grid data display</p>	
        /// <p><b>作成者	:</b>万岗</p>	
        /// <p><b>作成日	:</b>2008/09/10</p>	
        /// <p><b>修改历史  :</b></p>	
        /// </summary>
        /// <param type="string" name="strGoodID">货单编号</param>
        protected void ShowGrid(string strGoodID)
        {
            //ReturnValue rvGoods;
            MODEL.MOD_M007_GOODS modelM007=new XiaoGang.Soft.XGWMS.MODEL.MOD_M007_GOODS();
            modelM007.GOODS_ID=strGoodID;
            //rvGoods = bll_M007.GetSingleData(modelM007);
            //if (rvGoods.ErrorFlag == false)
            //{
            //    Method.MessageShow(rvGoods.ErrorID,dataName);
            //    return;
            //}

            //if (rvGoods.ResultDataSet.Tables[0].Rows.Count > 0)
            //{
            //    //lbGOODS_ID.Text = strGoodID;
            //    //lbGOODS_NM1.Text = rvGoods.ResultDataSet.Tables[0].Rows[0]["GOODS_NM1"].ToString();
            //    //lbGOODS_GROUP.Text = rvGoods.ResultDataSet.Tables[0].Rows[0]["GOODS_GROUP_NM"].ToString();
            //    //lbPROVIDER.Text = rvGoods.ResultDataSet.Tables[0].Rows[0]["PROVIDER"].ToString();
            //    //lbMEMO.Text = rvGoods.ResultDataSet.Tables[0].Rows[0]["MEMO"].ToString();
            //}

            //取得商品[进][出][总]合计
            //rvGoods = bll_M014BILLSCAN.GetAllUnits(strGoodID);
            //if (rvGoods.ErrorFlag == false)
            //{
            //    Method.MessageShow(rvGoods.ErrorID,dataName);
            //    return;
            //}
            //if (rvGoods.ResultDataSet.Tables[0].Rows.Count > 0)
            //{
            //    //lbAllUnits.Text = "入库：[" + rvGoods.ResultDataSet.Tables[0].Rows[0]["ALLUNITS_IN"].ToString()
            //    //    + "] 销售：[" + rvGoods.ResultDataSet.Tables[0].Rows[0]["ALLUNITS_OUT"].ToString()
            //    //    + "] 库存：[" + rvGoods.ResultDataSet.Tables[0].Rows[0]["ALLUNITS"].ToString()+"]";
            //}

            //rvGoods = bll_M014BILLSCAN.SearchStorageDetail(strGoodID);

            //if (rvGoods.ErrorFlag == false)
            //{
            //    Method.MessageShow(rvGoods.ErrorID,dataName);
            //    return;
            //}            
            //grdmentBillDetailInfo.Rows.Clear();
            //foreach (DataRow row in rvGoods.ResultDataSet.Tables[0].Rows)
            //{
            //    //grdmentBillDetailInfo.Rows.Add(
            //    //    (grdmentBillDetailInfo.Rows.Count + 1).ToString(),
            //    //    DateFormat(row["BUSINESS_TIME"].ToString().Replace("/","")),
            //    //    row["IN_OUT_Name"].ToString().Trim(),
            //    //    row["UNITS"].ToString().Trim(),
            //    //    row["PRICE"].ToString().Trim()== "-1.0000" ? "" : string.Format("{0:f2}",decimal.Parse(row["PRICE"].ToString().Trim())),
            //    //    row["MEMO"].ToString().Trim());
            //}
            //if (grdmentBillDetailInfo.Rows.Count > 17)
            //{
            //    grdmentBillDetailInfo.Columns["MEMO"].Width = 305;
            //}
            //else
            //{
            //    grdmentBillDetailInfo.Columns["MEMO"].Width = 322;
            //}
        }

        /// <summary>	
        /// <p><b>方法名称</b>DateFormat</p>	
        /// <p><b>概要説明  :</b>date data format</p>	
        /// <p><b>作成者	:</b>万岗</p>	
        /// <p><b>作成日	:</b>2008/09/10</p>	
        /// <p><b>修改历史  :</b></p>	
        /// </summary>
        /// <param name="strValue">没有格式化的字符串</param> 
        /// <returns type="string">格式化后的字符串</returns>
        protected string DateFormat(string strValue)
        {
            if (strValue.Length < 8)
            {
                return strValue;
            }
            return strValue.Substring(0, 4) + "/" +
                strValue.Substring(4, 2) + "/" +
                strValue.Substring(6, 2);

        }

        /// <summary>	
        /// <p><b>方法名称</b>NumPriceFormat</p>	
        /// <p><b>概要説明  :</b>num and price data format</p>	
        /// <p><b>作成者	:</b>万岗</p>	
        /// <p><b>作成日	:</b>2008/09/10</p>	
        /// <p><b>修改历史:</b></p>	
        /// </summary>
        /// <param name="strValue">没有格式化的字符串</param> 
        /// <returns type="string">格式化后的字符串</returns>
        protected string NumPriceFormat(string strValue)
        {
            string strTemp = strValue;
            if (strValue.Length > 6)
            {
                strTemp = strValue.Substring(0, strValue.Length - 6) + ","
                    + strValue.Substring((strValue.Substring(0, strValue.Length - 6)).Length, 3)
                    + "," + strValue.Substring(strValue.Length - 3, 3);

            }
            else if (strValue.Length > 3)
            {
                strTemp = strValue.Substring(0, strValue.Length - 3) + ","
                + strValue.Substring((strValue.Substring(0, strValue.Length - 3)).Length, 3);
            }
            return strTemp;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="myExcel"></param>
        /// <param name="dsData"></param>
        private void WriteExlWithDataTable(Excel.Application myExcel, DataSet dsData)
        {
            Excel.Workbook myBook = myExcel.Workbooks[1];
            Excel.Worksheet mySheet = (Excel.Worksheet)myBook.Worksheets[1];
            Excel.Range r;
            Excel.Range r1;
            for (int i = 0; i < dsData.Tables[0].Rows.Count; i++)
            {
                r = (Excel.Range)mySheet.Rows.get_Item(i + 6, Missing.Value);
                r.Copy(Missing.Value);
                r1 = (Excel.Range)mySheet.Rows.get_Item(i + 7, Missing.Value);
                r1.PasteSpecial(XlPasteType.xlPasteFormats, XlPasteSpecialOperation.xlPasteSpecialOperationNone, false, false);
                myExcel.Cells[i + 6, 1] = "'" + (i + 1).ToString();
                myExcel.Cells[i + 6, 2] = "'" + dsData.Tables[0].Rows[i]["GOODS_ID"].ToString();
                //myExcel.Cells[i + 6, 3] = "'" + dsData.Tables[0].Rows[i]["GOODS_NO"].ToString();
                myExcel.Cells[i + 6, 3] = "'" + dsData.Tables[0].Rows[i]["GOODS_NM1"].ToString();
                myExcel.Cells[i + 6, 4] = "'" + dsData.Tables[0].Rows[i]["GOODS_NM2"].ToString();
                myExcel.Cells[i + 6, 5] = "'" + dsData.Tables[0].Rows[i]["GOODS_GROUP"].ToString();
                myExcel.Cells[i + 6, 6] = "'" + dsData.Tables[0].Rows[i]["PROVIDER"].ToString();
                myExcel.Cells[i + 6, 7] = "'" + dsData.Tables[0].Rows[i]["PRODUCE_DATE"].ToString();
                myExcel.Cells[i + 6, 8] = "'" + dsData.Tables[0].Rows[i]["OVER_PRODUCE_DATE"].ToString();
                //myExcel.Cells[i + 6, 10] = "'" + dsData.Tables[0].Rows[i]["OVER_DATE"].ToString();
                //myExcel.Cells[i + 6, 11] = "'" + dsData.Tables[0].Rows[i]["MAX_WARN"].ToString();
                //myExcel.Cells[i + 6, 12] = "'" + dsData.Tables[0].Rows[i]["MIN_WARN"].ToString();
                myExcel.Cells[i + 6, 9] = "'" + dsData.Tables[0].Rows[i]["BUYING_PRICE"].ToString();
                myExcel.Cells[i + 6, 10] = "'" + dsData.Tables[0].Rows[i]["SELLING_PRICE"].ToString();
                //myExcel.Cells[i + 6, 15] = "'" + dsData.Tables[0].Rows[i]["MEMO"].ToString();
            }
        }

        /// <summary>
        /// SaveFile
        /// </summary>
        /// <param name="strMobanName"></param>
        /// <param name="filename"></param>
        private void SaveFile(string strMobanName, out string filename)
        {
            SaveFileDialog mySave = new SaveFileDialog();
            mySave.Filter = "Excelﾎﾄｼ(*.XLS)|*.xls|ﾋﾐﾎﾄｼ(*.*)|*.*";
            if (mySave.ShowDialog() != DialogResult.OK)
            {
                filename = null;
                return;
            }
            else
            {
                filename = mySave.FileName;
                string filenameold = mySave.FileName;
                FileInfo mode = new FileInfo(System.Windows.Forms.Application.StartupPath.Trim() + "\\" + strMobanName);
                try
                {
                    mode.CopyTo(filename, true);
                }
                catch (Exception ee)
                {
                    MessageBox.Show(ee.Message);
                    return;
                }
            }
        }

        /// <summary>
        /// 刷新备份列表
        /// </summary>
        private void InitDataBackList()
        {
            string strDataBackPath = AppDomain.CurrentDomain.BaseDirectory;
            string[] strBakFiles = Directory.GetFiles(strDataBackPath);
            if (strBakFiles.Length > 0)
            {
                listDataBaseBak.Items.Clear();
                //listDataBaseBak.Visible = true;
                foreach (string file in strBakFiles)
                {
                    FileInfo bakFile = new FileInfo(file);
                    if (bakFile.Extension.ToUpper() == ".BAK")
                    {
                        listDataBaseBak.Items.Add(bakFile.Name);
                    }
                }
            }
            else
            {
                listMessage.Items.Add(DateTime.Now.ToString("MM.dd HH:mm:ss") + ":没有备份文件，要使用还原功能请先进行备份！");
                return;
            }
        }

        #endregion

        #region 事件

        private void M013_STORAGE_Detail_Load(object sender, EventArgs e)
        {
            this.StartPosition = FormStartPosition.CenterScreen;
            InitProcess();
        }

        /// <summary>
        /// btnClose_Click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnClose_Click(object sender, EventArgs e)
        {
            if (this.Cursor == Cursors.WaitCursor)
            {
                return;
            }
            this.Close();
        }

        /// <summary>
        /// M013_STORAGE_Detail_KeyUp
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void M013_STORAGE_Detail_KeyUp(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
                case Keys.Escape:
                    btnClose_Click(sender, e);
                    break;
            }
        }

        /// <summary>
        /// 清除冗余货单信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnClearData_Click ( object sender, EventArgs e )
        {
            BLL.BLL_System bll=new XiaoGang.Soft.XGWMS.BLL.BLL_System();
            int ReCount = 0;
            //==================================================================
            //========================清除冗余货单信息============================
            //==================================================================
            string reValue = bll.DeleteBillGarbage (out ReCount);
            if ("0" == reValue)
            {
                listMessage.Items.Add(DateTime.Now.ToString("MM.dd HH:mm:ss") + ":清除冗余货单信息 " + ReCount.ToString() + " 条。");
            }
            else
            {
                listMessage.Items.Add(DateTime.Now.ToString("MM.dd HH:mm:ss") + ":清除冗余货单信息时发生异常，请与开发商取得联系以寻求帮助。错误代号:" + reValue);
            }
            //******************************************************************

            //==================================================================
            //========================清除冗余商品信息[已删除并且没有销售记录]=======
            //==================================================================
            reValue = bll.DeleteGoodsGarbage(out ReCount);
            if ("0" == reValue)
            {
                listMessage.Items.Add(DateTime.Now.ToString("MM.dd HH:mm:ss") + ":清除冗余商品信息 " + ReCount.ToString() + " 条。");
            }
            else
            {
                listMessage.Items.Add(DateTime.Now.ToString("MM.dd HH:mm:ss") + ":清除冗余商品信息时发生异常，请与开发商取得联系以寻求帮助。错误代号:" + reValue);
            }
            //******************************************************************

            //==================================================================
            //========================清除冗余商品分类信息[已删除并且没有被使用]=====
            //==================================================================
            reValue = bll.DeleteGoodsGroupGarbage(out ReCount);
            if ("0" == reValue)
            {
                listMessage.Items.Add(DateTime.Now.ToString("MM.dd HH:mm:ss") + ":清除冗余商品分类信息 " + ReCount.ToString() + " 条。");
            }
            else
            {
                listMessage.Items.Add(DateTime.Now.ToString("MM.dd HH:mm:ss") + ":清除冗余商品分类信息时发生异常，请与开发商取得联系以寻求帮助。错误代号:" + reValue);
            }
            //******************************************************************

            //==================================================================
            //========================清除冗余会员信息[已删除并且没有被使用]=========
            //==================================================================
            reValue = bll.DeleteMemberGarbage(out ReCount);
            if ("0" == reValue)
            {
                listMessage.Items.Add(DateTime.Now.ToString("MM.dd HH:mm:ss") + ":清除冗余会员信息 " + ReCount.ToString() + " 条。");
            }
            else
            {
                listMessage.Items.Add(DateTime.Now.ToString("MM.dd HH:mm:ss") + ":清除冗余会员信息时发生异常，请与开发商取得联系以寻求帮助。错误代号:" + reValue);
            }
            //******************************************************************
        }

        /// <summary>
        /// 清除消息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnClearMessage_Click ( object sender, EventArgs e )
        {
            listMessage.Items.Clear ();
        }

        /// <summary>
        /// 系统初始化
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnInitialization_Click ( object sender, EventArgs e )
        {
            if (DialogResult.Yes == Method.MessageShow("Q22015", dataName))//本操作将清除系统所有数据，确定要这样做吗?
            {
                listMessage.Items.Add(DateTime.Now.ToString("MM.dd HH:mm:ss") + ":对不起！暂时没有本权限。不过你的探索精神值得赞扬！");
            }
        }

        /// <summary>
        /// 数据库备份
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDataBackup_Click(object sender, EventArgs e)
        {
            string strPath = AppDomain.CurrentDomain.BaseDirectory + DateTime.Now.ToString ("yyyy_MM_dd HH_mm_ss") + ".bak";
            string strDataBaseName= GlobalVal.glostrDataBaseName;
            BLL.BLL_System bll=new XiaoGang.Soft.XGWMS.BLL.BLL_System();
            string strResoult = bll.BackUp (strDataBaseName, strPath);
            if ("0" == strResoult.Trim())
            {
                listMessage.Items.Add(DateTime.Now.ToString("MM.dd HH:mm:ss") + ":数据库备份成功，备份路径:" + strPath + " 请勿删除！");
                //刷新备份列表
                InitDataBackList();
            }
            else
            {
                listMessage.Items.Add(DateTime.Now.ToString("MM.dd HH:mm:ss") + ":数据库备份时发生异常，请与开发商取得联系以寻求帮助。错误代号:" + strResoult);
            }
        }

        /// <summary>
        /// 数据库还原
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDataRestore_Click(object sender, EventArgs e)
        {
            if (listDataBaseBak.Items.Count > 0)
            {
                if (listDataBaseBak.SelectedItem == null)
                {
                    listMessage.Items.Add(DateTime.Now.ToString("MM.dd HH:mm:ss") + ":请先选择一个要还原的数据库备份。");
                    return;
                }
                if (DialogResult.Yes == Method.MessageShow("Q22016", dataName))//确定要进行数据库还原功能吗？请确要还原的文件是当前所选择的！
                {
                    string strPath = AppDomain.CurrentDomain.BaseDirectory;
                    strPath += listDataBaseBak.SelectedItem.ToString();
                    string strDataBaseName = GlobalVal.glostrDataBaseName;
                    BLL.BLL_System bll = new XiaoGang.Soft.XGWMS.BLL.BLL_System();
                    string strResoult = bll.ReStore(strDataBaseName, strPath);
                    if ("0" == strResoult.Trim())
                    {
                        listMessage.Items.Add(DateTime.Now.ToString("MM.dd HH:mm:ss") + ":数据库还原成功！");
                        //listDataBaseBak.Visible = false;
                    }
                    else
                    {
                        listMessage.Items.Add(DateTime.Now.ToString("MM.dd HH:mm:ss") + ":数据库还原时发生异常，请与开发商取得联系以寻求帮助。错误代号:" + strResoult);
                        //listDataBaseBak.Visible = false;
                    }
                }
            }
            else
            {
                listMessage.Items.Add(DateTime.Now.ToString("MM.dd HH:mm:ss")+ ":没有备份文件，要使用还原功能请先进行备份！");
            }




            //string strPath = AppDomain.CurrentDomain.BaseDirectory;
            //string[] strBakFiles = Directory.GetFiles (strPath);
            //if(strBakFiles.Length>0)
            //{
            //    listDataBaseBak.Items.Clear ();
            //    listDataBaseBak.Visible = true;
            //    foreach (string file in strBakFiles)
            //    {
            //        FileInfo bakFile = new FileInfo (file);
            //        if (bakFile.Extension.ToUpper() == ".BAK")
            //        {
            //            listDataBaseBak.Items.Add (bakFile.Name);
            //        }                    
            //    }
            //}
            //else
            //{
            //    listMessage.Items.Add ("没有备份文件，要使用还原功能请先进行备份！");
            //    return;
            //}            
        }

        private void listDataBaseBak_DoubleClick ( object sender, EventArgs e )
        {
            //if (listDataBaseBak.Items.Count>0)
            //{
            //    if(DialogResult.Yes == Method.MessageShow ("Q22016"))//确定要进行数据库还原功能吗？请确要还原的文件是当前所选择的！
            //    {
            //        string strPath = AppDomain.CurrentDomain.BaseDirectory;
            //        strPath += listDataBaseBak.SelectedItem.ToString ();
            //        string strDataBaseName = GlobalVal.glostrDataBaseName;
            //        BLL.BLL_System bll = new XiaoGang.Soft.XGWMS.BLL.BLL_System ();
            //        string strResoult = bll.ReStore (strDataBaseName, strPath);
            //        if ("0" == strResoult.Trim ())
            //        {
            //            listMessage.Items.Add ("数据库还原成功！");
            //            listDataBaseBak.Visible = false;
            //        }
            //        else
            //        {
            //            listMessage.Items.Add ("数据库还原时发生异常，请与开发商取得联系以寻求帮助。错误代号:" + strResoult);
            //            listDataBaseBak.Visible = false;
            //        }
            //    }
            //}
        }

        #endregion
    }
}